package com.neasho.neashoadminv1.infrastructure.domain

import com.neasho.neashoadminv1.infrastructure.utils.MDCUtils
import org.springframework.http.HttpStatus


/**
 * 接口统一返回值
 */
class R<V>(
    var code: Int,
    var message: String,
    var data: V?,
    var traceId: String = MDCUtils.traceId
) {
    companion object {
        fun <V> ok(): R<V> {
            return R(HttpStatus.OK.value(), "success", null)
        }
        fun <V> ok(code:Int, message: String): R<V> {
            return R(code, message, null)
        }
        fun <V> ok(data: V?): R<V> {
            return R(HttpStatus.OK.value(), "success", data)
        }

        fun <V> error(code: Int, message: String, data: V? = null): R<V> {
            return R(code, message, data)
        }

        fun <V> error(message: String): R<V> {
            return error(HttpStatus.INTERNAL_SERVER_ERROR.value(), message, null)
        }

        fun affect(b: Boolean):R<Boolean> {
            return if (b) {
                ok(HttpStatus.OK.value(), "Operation success")
            } else {
                error("Operation failed")
            }
        }

        fun affect(rows:Int):R<Int> {
            return if (rows > 0) {
                R(HttpStatus.OK.value(), "Operation success", rows)
            } else {
                error("Operation failed")
            }
        }

    }
    private var httpStatusCode: HttpStatus? = null

    /**
     * 设置http状态码
     */
    fun setHttpStatusCode(httpStatus: HttpStatus) {
        this.httpStatusCode = httpStatus
    }

    /**
     * 返回http状态码，如果没有设置，则根据code返回对应的http状态码
     */
    fun httpStatus(): HttpStatus? = httpStatusCode ?: HttpStatus.valueOf(code)

}